package com.yihu.wlyy.task;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import com.yihu.wlyy.util.SystemConf;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.WxTemplate;
import com.yihu.wlyy.entity.WxTemplateData;
import com.yihu.wlyy.util.HttpUtil;

@Controller
@RequestMapping(value = "/pushMsgTask")
public class PushMsgTask {

	private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();

	private static PushMsgTask instance;

	private static Object lock = new Object();

	public static PushMsgTask getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new PushMsgTask();
				instance.run();
			}
		}
		return instance;
	}

	@RequestMapping(value = "aa")
	@ResponseBody
	public String test() {
		return "1111";
	}

	/**
	 * 添加一条推送消息
	 * @param receiver 接收人
	 * @param type 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public void put(String receiver, String type, String title, String msg, String data) {
		try {
			JSONObject json = new JSONObject();
			json.put("receiver", receiver);
			json.put("type", type);
			json.put("title", title);
			json.put("msg", msg);
			json.put("data", data);
			queue.put(json);
		} catch (Exception e) {
			logger.error("添加到消息队列失败！", e);
			e.printStackTrace();
		}
	}

	/**
	 * 添加微信消息
	 * @param type
	 * @param data
	 */
	public void putWxMsg(String access_token, int type, String openid, String name, JSONObject data) {
		try {
			JSONObject json = new JSONObject();
			json.put("wx", true);
			json.put("access_token", access_token);
			json.put("type", type);
			json.put("openid", openid);
			json.put("name", name);
			json.put("data", data);
			queue.put(json);
		} catch (Exception e) {
			logger.error("添加到微信消息列队列失败！", e);
			e.printStackTrace();
		}
	}

	public void put(JSONArray array) {
		if (array == null || array.length() == 0) {
			return;
		}
		for (int i = 0; i < array.length(); i++) {
			JSONObject json = array.getJSONObject(i);
			if (json == null) {
				continue;
			}
			try {
				queue.put(json);
			} catch (Exception e) {
				logger.error("批量添加到消息队列失败！", e);
			}
		}
	}

	private void run() {
		new Thread(new ConsumerTask()).start();
	}

	// 消费者
	class ConsumerTask implements Runnable {
		@Override
		public void run() {
			try {
				while (true) {
					// 如果queue为空，则当前线程会堵塞，直到有新数据加入
					JSONObject json = queue.take();
					boolean wx = json.has("wx") ? json.getBoolean("wx") : false;
					if (wx) {
						// 推送微信消息
						JSONObject data = json.has("data") ? json.getJSONObject("data") : null;
						if (data == null) {
							continue;
						}
						// 消息类型：1：签约成功 2：签约失败 3：咨询回复通知 4：健康指导提醒
						int type = json.has("type") ? json.getInt("type") : -1;
						if (type == -1) {
							continue;
						}
						String access_token = json.has("access_token") ? json.getString("access_token") : "";
						String openid = json.has("openid") ? json.getString("openid") : "";
						String name = json.has("name") ? json.getString("name") : "";
						// 发送消息到微信端
						sendWeixinMessage(access_token, type, openid, name, data);
					} else {
						// 推送平台消息
						String receiver = json.has("receiver") ? json.getString("receiver") : "";
						String type = json.has("type") ? json.getString("type") : "";
						String title = json.has("title") ? json.getString("title") : "";
						String msg = json.has("msg") ? json.getString("msg") : "";
						String data = json.has("data") ? json.getString("data") : "";
						boolean res = HttpUtil.pushMessage(receiver, type, title, msg, data);
						if (res) {
							logger.info("消息推送成功！");
						} else {
							logger.error("消息推送失败！");
						}
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

//	private static final String signSuccess = "0D2vYZVRzFz15p9Y_pkZ1DKutDq8UOsks79FXUKS0tA";
//	private static final String signFalied = "My2VNERjJt4NXR4Ibh42pdrP6B6ka8rQxZeWinQh99s";
//	private static final String consultNotice = "0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc";
//	private static final String healthNotice = "uv31ES_VCmq3tBYtyGmEQvIwU_zh9LDhF3bFpbIUt5g";
//	private static final String termination = "C0tdXtA_8k-Cy4a1EkzQuI877vqaqAtRkc-e_Gsd7sk";
//	private static final String appointmentSuccess = "FY3Pqa66tHIE1Fv-irbFBPOh5cYP71fkOzfZKH4S-Fo";
//	private static final String appointmentCancel = "tldWEb9AN7p_RoHoD8ml0GxWW3V1V_mpEEhp2v6p56s";
	private static final String url = "http://www.xmtyw.cn/wlyy/wx/html/";

	/**
	 * 发送微信模板消息
	 * @param type 1：签约成功  2：签约失败  3：咨询回复通知  4：健康指导提醒  5：解约申请通知  6：预约挂号成功通知  7：预约取消通知
	 * @param json 当type==1||type==2时：{"first":"消息主题",”doctor":"医生code","doctorName":"医生名","date":"签约时间","content":"签约内容","remark":"消息备注"}
	 *        type==3时：{"first":"消息主题","consult":"医生咨询编号","consultcontent":"咨询内容","replycontent":"回复内容","doctorName":"医生名","remark":"消息备注"}
	 *        type==4时：{"first":"消息主题","date":"指导时间","orgName":"指导机构","doctorName":"指导医生名","content":"指导内容","remark":"消息备注"}
	 *        type==5时：{"first":"消息主题","date":"解约时间",”doctor":"医生code","doctorName":"医生名","orgName":"解约机构","remark":"消息备注"}
	 *        type==6时：{"first":"消息主题","date":"预约时间",”id":"预约ID","doctorName":"医生名","orgName":"预约医院","deptName":"预约科室","remark":"消息备注"}
	 *        type==7时：{"first":"消息主题","name":"就诊人名","date":"预约时间","doctorName":"医生名","orgName":"预约医院","remark":"消息备注"}
	 * @return
	 */
	private boolean sendWeixinMessage(String access_token, int type, String openid, String name, JSONObject json) {
		try {
			if (access_token != null) {
				String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
				String params = typeMsg(type, openid, name, json);
				if (params == "") {
					logger.error("参数错误！");
					return false;
				}
				String result = HttpUtil.sendPost(token_url, params);
				JSONObject jsonResult = new JSONObject(result);
				if (Integer.parseInt(jsonResult.get("errcode").toString()) == 0) {
					logger.info("微信信息推送成功！");
					return true;
				} else {
					logger.error("错误编码：" + jsonResult.get("errcode").toString() + "  错误提示:" + jsonResult.get("errmsg").toString());
					return false;
				}
			} else {
				logger.error("获取access_token失败！");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("微信信息推送失败！");
			return false;
		}
	}

	/**
	 * 拼接参数
	 * @param type
	 * @return
	 */
	public String typeMsg(int type, String openid, String name, JSONObject json) {
		try {
			WxTemplate temp = new WxTemplate();
			temp.setTouser(openid);
			temp.setTopcolor("#000000");
			Map<String, WxTemplateData> m = new HashMap<String, WxTemplateData>();
			WxTemplateData first = new WxTemplateData();
			first.setColor("#000000");
			first.setValue(json.getString("first"));
			m.put("first", first);
			WxTemplateData remark = new WxTemplateData();
			remark.setColor("#000000");
			remark.setValue(json.getString("remark"));
			m.put("remark", remark);
			String temp_id = "";
			if (type == 3) {
				temp.setUrl(url + "yszx/html/consulting-doctor.html?openid=" + openid + "&consult=" + json.getString("consult"));
				temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_consult_notice");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("consultcontent"));
				m.put("keyword1", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(json.getString("replycontent"));
				m.put("keyword2", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("doctorName"));
				m.put("keyword3", keyword3);
			} else if (type == 1 || type == 2) {				
				if (type == 1)				
					temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_sign_success");
				else
					temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_sign_failed");
				temp.setUrl(url + "ssgg/html/doctor-homepage-new.html?openid=" + openid  + "&state=" + json.getString("doctor"));
				temp.setTouser(openid);
				temp.setTopcolor("#000000");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("doctorName"));
				m.put("keyword1", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(name);
				m.put("keyword2", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("date"));
				m.put("keyword3", keyword3);
				WxTemplateData keyword4 = new WxTemplateData();
				keyword4.setColor("#000000");
				keyword4.setValue(json.getString("content"));
				m.put("keyword4", keyword4);
			} else if (type == 4) {
				temp.setUrl(url + "yszd/html/doctor-guidance.html?openid=" + openid);
				temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_health_notice");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("date"));
				m.put("keyword1", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(json.getString("orgName"));
				m.put("keyword2", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("doctorName"));
				m.put("keyword3", keyword3);
				WxTemplateData keyword4 = new WxTemplateData();
				keyword4.setColor("#000000");
				keyword4.setValue(name);
				m.put("keyword4", keyword4);
				WxTemplateData keyword5 = new WxTemplateData();
				keyword5.setColor("#000000");
				keyword5.setValue(json.getString("content"));
				m.put("keyword5", keyword5);
			} else if (type == 5) {
				temp.setUrl(url + "ssgg/html/doctor-homepage-new.html?openid=" + openid  + "&state=" + json.getString("doctor"));
				temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_termination");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("doctorName"));
				m.put("keyword1", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(name);
				m.put("keyword2", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("orgName"));
				m.put("keyword3", keyword3);
				WxTemplateData keyword4 = new WxTemplateData();
				keyword4.setColor("#000000");
				keyword4.setValue(json.getString("date"));
				m.put("keyword4", keyword4);
			} else if (type == 6) {
				temp.setUrl(url + "wdyy/html/detail-appointment.html?openid=" + openid +"&id=" + json.getLong("id"));
				temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_appoint_success");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("orgName"));
				m.put("hospitalname", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(json.getString("deptName"));
				m.put("deptname", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("doctorName"));
				m.put("doctorname", keyword3);
				WxTemplateData keyword4 = new WxTemplateData();
				keyword4.setColor("#000000");
				keyword4.setValue(json.getString("date"));
				m.put("planstarttime", keyword4);
			} else if (type == 7) {
				temp.setUrl(url + "wdyy/html/my-appointment.html?openid=" + openid);
				temp_id = SystemConf.getInstance().getSystemProperties().getProperty("template_appoint_failed");
				temp.setTemplate_id(temp_id);
				WxTemplateData keyword1 = new WxTemplateData();
				keyword1.setColor("#000000");
				keyword1.setValue(json.getString("name"));
				m.put("keynote1", keyword1);
				WxTemplateData keyword2 = new WxTemplateData();
				keyword2.setColor("#000000");
				keyword2.setValue(json.getString("date"));
				m.put("keynote2", keyword2);
				WxTemplateData keyword3 = new WxTemplateData();
				keyword3.setColor("#000000");
				keyword3.setValue(json.getString("doctorName"));
				m.put("keynote3", keyword3);
				WxTemplateData keyword4 = new WxTemplateData();
				keyword4.setColor("#000000");
				keyword4.setValue(json.getString("orgName"));
				m.put("keynote4", keyword4);
			}
			temp.setData(m);
			ObjectMapper mapper = new ObjectMapper();
			String strJson = mapper.writeValueAsString(temp);
			return strJson;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

}